package com.ljw.security.distributedsecurityuaa.dao;

import com.ljw.security.distributedsecurityuaa.model.PermissionDto;
import com.ljw.security.distributedsecurityuaa.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @FileName UserDao
 * @Description TODO
 * @Author ljw
 * @Date 2020/9/2 12:35
 * @Version 1.0
 */
@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //根据账号从数据库用户表查询用户信息
    public UserDto getUserByUsername(String username){
        String sql ="select id,username,password,fullname from t_user where username = ?";

        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if(list!= null && list.size() > 0){
            return list.get(0);

        }
        return null;

    }

    //根据userId从数据库查询用户权限信息
    public List<PermissionDto>  findPermissionsByUserId(String userId){

        String sql="SELECT * FROM t_permission WHERE id IN(SELECT permission_id FROM t_role_permission WHERE role_id IN(SELECT role_id FROM t_user_role WHERE user_id = ? ))";
        List<PermissionDto> permissionDtos = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));
        if (permissionDtos!=null&&permissionDtos.size()>0){
            return permissionDtos;
        }
        return null;

    }
}
